package com.wfcm.wxPay;

import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;
import com.wfcm.utils.ConstantUtil;
import com.wfcm.utils.XMLUtil;

/**
 * 支付成功后订单查询
 * @author Sunlight
 *
 */
public class WXOrderQuery {
	private String partnerKey;
	private String appid;
	private String mch_id;
	private String transaction_id;
	private String out_trade_no;
	private String nonce_str;
	private String sign;
	
	//请求订单查询接口
	public Map<String, String> reqOrderquery(){
		// 创建HttpClientBuilder
		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
		// HttpClient
		CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
		HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/pay/orderquery");
		String xml = getPackage();
		System.out.println(xml);
		StringEntity entity;
		Map<String, String> map = null;
		try {
			entity = new StringEntity(xml, "utf-8");
			httpPost.setEntity(entity);

			HttpResponse httpResponse;
			// post请求
			httpResponse = closeableHttpClient.execute(httpPost);

			// getEntity()
			HttpEntity httpEntity = httpResponse.getEntity();
			if (httpEntity != null) {
				// 打印响应内容
				String result = EntityUtils.toString(httpEntity, "UTF-8");
				// 过滤
				result = result.replaceAll("<![CDATA[|]]>", "");
				map = XMLUtil.doXMLParse(result);
				System.out.println("支付金额："+map.get("total_fee"));
				System.out.println(result);
			}
			// 释放资源
			closeableHttpClient.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}
	
	public String getPackage() {
		TreeMap<String, String> treeMap = new TreeMap<String, String>();
		treeMap.put("appid", this.appid);
		treeMap.put("mch_id", this.mch_id);
		//treeMap.put("transaction_id", this.transaction_id);
		treeMap.put("nonce_str", this.nonce_str);
		treeMap.put("out_trade_no", this.out_trade_no);
		
		StringBuilder sb = new StringBuilder();
		for (String key : treeMap.keySet()) {
			sb.append(key).append("=").append(treeMap.get(key)).append("&");
		}
		sb.append("key=" + partnerKey);
		sign = MD5Util.MD5Encode(sb.toString(), "utf-8").toUpperCase();
		treeMap.put("sign", sign);

		StringBuilder xml = new StringBuilder();
		xml.append("<xml>\n");

		for (Map.Entry<String, String> entry : treeMap.entrySet()) {
			if ("body".equals(entry.getKey()) || "sign".equals(entry.getKey())) {
				xml.append("<" + entry.getKey() + "><![CDATA[").append(entry.getValue()).append("]]></" + entry.getKey() + ">\n");
			} else {
				xml.append("<" + entry.getKey() + ">").append(entry.getValue()).append("</" + entry.getKey() + ">\n");
			}
		}
		xml.append("</xml>");
		return xml.toString();
	}
	
	public static void main(String[] args) throws Exception {
 
		String orderNum = "8296834487159804";
   	 // 商户相关资料
       String appid = ConstantUtil.APP_ID;
       // String appsecret = ConstantUtil.APP_SECRET;
       String partner = ConstantUtil.PARTNER;
       String partnerkey = ConstantUtil.PARTNER_KEY;
   	
	   	WXOrderQuery query = new WXOrderQuery();
	   	query.setAppid(appid);//应用APPID
	   	query.setMch_id(partner);//商户号
	   	Random random = new Random();
		String randomStr = MD5Util.MD5Encode(String.valueOf(random.nextInt(1000000)), "utf-8").toUpperCase();
		System.out.println("randomStr="+randomStr);
		query.setNonce_str(MD5Util.MD5Encode(randomStr, "utf-8").toLowerCase());//随机字符串
	   	query.setOut_trade_no(orderNum);//商户订单号
	   	query.setPartnerKey(partnerkey);//API秘钥
	   	query.setSign(createSign(query, partnerkey));//签名
	   	//query.setTransaction_id(transactionId);//微信订单号(或商户订单号 二选一)
	   	
	   	Map map = query.reqOrderquery();
		
        System.out.println(map);
    }
	 /**
	 * 创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
	 */
	public static String createSign(WXOrderQuery query, String AppKey) {
		SortedMap<String, String> nativeObj = new TreeMap<String, String>();
		nativeObj.put("appid", query.getAppid());
		nativeObj.put("mchid", query.getMch_id());
		nativeObj.put("noncestr", query.getNonce_str());
		nativeObj.put("outtradeno", query.getOut_trade_no());
		StringBuffer sb = new StringBuffer();
		Set es = nativeObj.entrySet();
		Iterator it = es.iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
				sb.append(k + "=" + v + "&");
			}
		}
		sb.append("key=" + AppKey);
		System.out.println("sb="+sb.toString());
		String sign = MD5Util.MD5Encode(sb.toString(), "UTF-8").toUpperCase();
		return sign;
	}
	
	public String getAppid() {
		return appid;
	}
	public void setAppid(String appid) {
		this.appid = appid;
	}
	public String getMch_id() {
		return mch_id;
	}
	public void setMch_id(String mchId) {
		mch_id = mchId;
	}
	public String getTransaction_id() {
		return transaction_id;
	}
	public void setTransaction_id(String transactionId) {
		transaction_id = transactionId;
	}
	public String getOut_trade_no() {
		return out_trade_no;
	}
	public void setOut_trade_no(String outTradeNo) {
		out_trade_no = outTradeNo;
	}
	public String getNonce_str() {
		return nonce_str;
	}
	public void setNonce_str(String nonceStr) {
		nonce_str = nonceStr;
	}
	public String getSign() {
		return sign;
	}
	public void setSign(String sign) {
		this.sign = sign;
	}

	public String getPartnerKey() {
		return partnerKey;
	}

	public void setPartnerKey(String partnerKey) {
		this.partnerKey = partnerKey;
	}
	
}
